import datetime
import os
import time
from bilibili_update import format_to_mysql
import logzero
import requests
from logzero import logger
from lxml import html
from mysql_conf import mysel_conf
'''
bilibili 单爬 av号
'''
current_module = os.path.splitext(os.path.basename(__file__))[0]
logzero.logfile(f"/tmp/{current_module}.log", maxBytes=30_000_000, backupCount=3, encoding='utf-8')


def get_mid(avNum):
    url = f'https://www.bilibili.com/video/av{avNum}/'
    logger.info('av号' + avNum)
    req=requests.get(url)
    if req.status_code!=200:
        logger.info('av号错误')
        return False , avNum
    page = html.fromstring(requests.get(url).content)

    mid = page.cssselect('.message')
    if len(mid) > 0:
        mid_id = mid[0].get('mid')
        if mid_id==None:
            mid_id =int(mid[0].get('href').split('mid')[1])
    else:
        mid_id = 0
    author_img_ele = page.cssselect('#r-info-rank > a:nth-child(1) > img')
    print(len(author_img_ele))
    if len(author_img_ele) > 0:
        author_img = 'http:' + author_img_ele[0].attrib['src']
    else:
        author_img = ''

    return author_img,  mid_id


def get_info(mid, avNum):
    p = 1
    stop = False
    while not stop:
        index_url = f'https://space.bilibili.com/ajax/member/getSubmitVideos?mid={mid}&pagesize=100&tid=0&page={p}&keyword=&order=pubdate'
        logger.info(index_url)
        resp = requests.get(index_url).json()
        vlist = resp['data']['vlist']
        if not vlist:
            # loggler.info('翻页结束')
            break
        for data in vlist:
            if data['aid'] == int(avNum):
                data['pic'] = 'http:' + data['pic']
                return data
            # stop = store_data(data)
            if stop: break
        p += 1
        # logger.info('翻页')

def get_tag(aid):
    tags = requests.get(f'https://api.bilibili.com/x/tag/archive/tags?aid={aid}').json()
    tag = []
    for i in tags['data']:
        tag.append(i['tag_name'])
    return tag

def get_tag_id(tag):
    tag_id=[]
    conn = mysel_conf.pool()
    cursor = conn.cursor()
    if len(tag)==0:
        return False
    for t in tag:
        get_tag_from_theme_id = "SELECT id FROM tag WHERE name = %s"

        cursor.execute(get_tag_from_theme_id, (t,))  # 读tag
        result = cursor.fetchone()
        if not result:
            insert="INSERT INTO tag (name,op_time,status)VALUES(%s,%s,%s)"
            cursor.execute(insert, (t,'0000-00-00 00:00:00',0,))  # 读tag
            id = int(cursor.lastrowid)
            tag_id.append(id)
            conn.commit()
        else:
            tag_id.append(result['id'])
    return tag_id
def main(aid, adminName,theme_id):
    a = time.time()
    if not  get_mid(aid):
        logger.info('bilibili输入错误')
        return False, aid
    try:
        author_img,  mid = get_mid(aid)

        info = get_info(mid, aid)
        logger.info('bilibili指定爬取结束')
        format_mysql={}
        format_mysql=format_to_mysql(info,theme_id)
        tag=get_tag(aid)
        format_mysql['type']=get_tag_id(tag)

        if len(tag)>0:
            logger.error(f'error from bilibili_one__{format_mysql}')
            return True,format_mysql
        else:
            logger.error(f'error from bilibili_one__{aid}')
            return False, False
    except (TypeError, KeyError) as e :
        logger.error('error from bilibili_one')
        logger.error(e)
        return False,False

if __name__ == '__main__':

   # a,b= main('791406', 'admin',1)
   # print(b)
    a,b=get_mid('19294802')
    print(a)
    print(b)

